package com.neusoft.baidu.controller;

import com.alibaba.fastjson.JSON;
import com.neusoft.baidu.entity.ExcelEntity;
import com.neusoft.baidu.util.BdOcrHelper;
import com.neusoft.baidu.util.ExcelImportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.util.PoiPublicUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.jeecg.common.api.vo.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 百度文字识别
 * @Author: zhengdc
 * @Date: 2019-12-03
 * @Version: V2.0
 */
@Api(tags = "百度文字识别")
@RestController
@RequestMapping("/ocr/identify")
public class BdOcrController {
    private final static Logger log = LoggerFactory.getLogger(BdOcrController.class);

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * 根据模板编号获取识别结果
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "上传需识别的图片", notes = "上传需识别的图片")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            String bizPath = "files";
            String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
            String orgName = mf.getOriginalFilename();// 获取文件名
            fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            result.setMessage(dbpath);
            result.setSuccess(true);
        } catch (IOException e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据模板编号获取识别结果
     *
     * @param requestObject
     * @return
     */
    @ApiOperation(value = "根据模板编码和图片路径进行识别", notes = "根据模板编码和图片路径进行识别")
    @PostMapping(value = "/gettemp")
    public Result<JSONObject> gettemp(@RequestBody JSONObject requestObject) {
        Result<JSONObject> result = new Result<>();
        String ctxPath = uploadpath;
        String bizPath = "files";
        String dbpath = ctxPath + File.separator + requestObject.getString("dbpath");
        String tempId = requestObject.getString("tempId");
        BdOcrHelper bdOcrHelper = new BdOcrHelper();
        JSONObject jsonObject = JSONObject.parseObject(bdOcrHelper.getTempInfo(tempId, dbpath).toString());
        result.setResult(jsonObject);
        result.setMessage("识别成功");
        result.setSuccess(true);
        return result;
    }

    /**
     * 获取增值税发票识别结果
     *
     * @param requestObject
     * @return
     */
    @ApiOperation(value = "根据图片路径进行识别", notes = "根据图片路径进行识别")
    @PostMapping(value = "/getinvoic")
    public Result<JSONObject> getinvoic(@RequestBody JSONObject requestObject) {
        Result<JSONObject> result = new Result<>();
        String ctxPath = uploadpath;
        String bizPath = "files";
        String dbpath = ctxPath + File.separator + requestObject.getString("dbpath");
        BdOcrHelper bdOcrHelper = new BdOcrHelper();
        JSONObject jsonObject = JSONObject.parseObject(bdOcrHelper.getVatInvoice(dbpath).toString());
        result.setResult(jsonObject);
        result.setMessage("识别成功");
        result.setSuccess(true);
        return result;
    }

    /**
     * 获取excel表数量
     *
     * @param requestObject
     * @return
     */
    @ApiOperation(value = "根据文件路径进行读取表数量", notes = "根据文件路径进行读取表数量")
    @PostMapping(value = "/getexcelcount")
    public Result<List<Map<String, Object>>> getexcelcount(@RequestBody JSONObject requestObject) {
        Result<List<Map<String, Object>>> result = new Result<>();
        String ctxPath = uploadpath;
        String dbpath = ctxPath + File.separator + requestObject.getString("dbpath");

        File file = new File(dbpath);
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        List<Map<String, Object>> names = ExcelImportUtil.showExcel(file);

        result.setResult(names);
        result.setMessage("存在多种表");
        result.setCode(1);
        result.setSuccess(true);
        return result;
    }

    /**
     * 获取excel内容结果
     *
     * @param requestObject
     * @return
     */
    @ApiOperation(value = "根据文件路径进行读取", notes = "根据文件路径进行读取")
    @PostMapping(value = "/getexcel")
    public Result<List<ExcelEntity>> getexcel(@RequestBody JSONObject requestObject) {
        Result<List<ExcelEntity>> result = new Result<>();
        String ctxPath = uploadpath;
        String dbpath = ctxPath + File.separator + requestObject.getString("dbpath");
        ImportParams params = new ImportParams();
        params.setTitleRows(2);
        params.setHeadRows(1);
        params.setNeedSave(true);
        File file = new File(dbpath);

        int num = requestObject.getInteger("num");
        params.setSheetNum(num + 1);
        List<ExcelEntity> list = ExcelImportUtil.importExcelIndex(file, ExcelEntity.class, params);

        List<Map<String, Object>> keys = new ArrayList<>();
        Field[] fileds = PoiPublicUtil.getClassFields(ExcelEntity.class);
        for(int i = 0; i < fileds.length; ++i) {
            Map<String, Object> key = new HashMap<>();
            key.put("index", i);
            Field field = fileds[i];
            Excel excel = (Excel)field.getAnnotation(Excel.class);
            if (excel != null) {
                String name = excel.name();
                key.put("key", name);
            }
            else {
                key.put("key", "");
            }
            key.put("field", field.getName());
            keys.add(key);
        }
        result.setResult(list);
        result.setMessage(JSON.toJSONString(keys));
        result.setCode(2);
        result.setSuccess(true);
        return result;
    }
}
